package top.xcxdl.rural.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created by IntelliJ IDEA.
 * 配置redis缓存
 * @Author : Ding
 * @create 2022/4/8 22:35
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
     * @param contextFactory redis连接工厂
     * @return redisTemplate
     */
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory contextFactory){
        RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();

        //默认的key序列化器为JdkSerializationRedisSerializer，这里改成StringRedisSerializer
        //原因是，默认的序列化器会造成 name => \xac\xed\x00\x05t\x00\x04name
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setConnectionFactory(contextFactory);
        return redisTemplate;
    }
}
